﻿using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Text;

namespace JX.Dapper
{
    /// <summary>
    /// Dapper服务扩展类
    /// </summary>
    public static class DapperDBContextServiceCollectionExtensions
    {
        /// <summary>
        /// 添加DapperDBContext和IUnitOfWorkFactory、IDapperDBContextFactory到DI中。
        /// 使用方法：在展示层的Startup.cs文件的ConfigureServices方法中，添加services.AddDapperDBContext《MyDapperDBContext》(options => {options.Configuration = @"server=127.0.0.1;database=ormdemo;uid=root;pwd=password;";});
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="services"></param>
        /// <param name="setupAction"></param>
        /// <returns></returns>
        public static IServiceCollection AddDapperDBContext<T>(this IServiceCollection services, Action<DapperDBContextOptions> setupAction) where T : DapperDBContext
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            if (setupAction == null)
            {
                throw new ArgumentNullException(nameof(setupAction));
            }

            services.AddOptions();
            services.Configure(setupAction);
            services.AddScoped<DapperDBContext, T>();//注入DapperDBContext依赖
            services.AddScoped<IUnitOfWorkFactory, DapperUnitOfWorkFactory>();//注入Uow依赖
            services.AddScoped<IDapperDBContextFactory, DapperDBContextFactory>();//注入DapperDBContextFactory依赖
            return services;
        }
    }
}
